package com.yc.ycrpc.clien;

import com.yc.ycrpc.Peer;
import com.yc.ycrpc.ReflectionUtils;
import com.yc.ycrpc.transport.TransportClient;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author yc112
 */
@Slf4j
public class RandomTransportSelector implements TransportSelector{

    // 已经连接好的client
    private List<TransportClient> clients;

    public RandomTransportSelector() {
        clients = new ArrayList<>();
    }

    /**
     *
     * @param peers 可以连接的server端点信息
     * @param count client与server建立多少个连接
     * @param clz client实现class
     */
    @Override
    public synchronized void init(List<Peer> peers, int count, Class<? extends TransportClient> clz) {
        count = Math.max(count, 1);
        // 首先循环连接
        for (Peer peer : peers) {
            // 再确认需要多少个链接
            for (int i = 0; i < count; i++) {
                TransportClient transportClient = ReflectionUtils.newInstance(clz);
                transportClient.connect(peer);
                clients.add(transportClient);
            }
            log.info("connect server {}", peer);
        }
    }

    @Override
    public synchronized TransportClient select() {
        int i = new Random().nextInt(clients.size());
        return clients.get(i);
    }

    @Override
    public synchronized void release(TransportClient client) {
        clients.add(client);
    }

    @Override
    public synchronized void close() {
        for (TransportClient client : clients) {
            client.close();
        }
        clients.clear();
    }
}
